package com.apesay.security;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Date;

public class ApiAuthData {
	private String secretKey="keegoo!@#$$#@!zxcvbnmplqawsokdekiujrfhytg";
	private boolean authed=false;
	private String userId;
	private String sessionToken;
	private long getTimeStamp(){
		return new Date().getTime();
	}
	/**
	 * 生成签名算法
	 * 如果未登录，则签名为：md5(timestamp+secretKey)
	 * 如果已登录，则签名为：md5(userId+sessionToken+timestamp+secretKey)
	 * @param timestamp
	 * @return
	 */
	private String generateSign(long timestamp){
		if(authed){
			String source=userId+sessionToken+timestamp+secretKey;
			return DigestUtils.md5Hex(source).toLowerCase();
		}else{
			String source=timestamp+secretKey;
			return DigestUtils.md5Hex(source).toLowerCase();
		}
	}
	/**
	 * 为请求参数追加公共鉴权参数
	 * @param object
	 */
	public void appendAuthParams(JSONObject object){
		if(object==null){
			object=new JSONObject();
		}
		if(authed){
			//如果已经登录，签名为md5(userId+sessionToken+timestamp+secretKey)
			object.put("userId", userId);
			object.put("sessionToken", sessionToken);
			long timeStamp=getTimeStamp();
			object.put("timestamp",timeStamp);
			object.put("sign", generateSign(timeStamp));
		}else{
			long timeStamp=getTimeStamp();
			object.put("timestamp",timeStamp);
			object.put("sign", generateSign(timeStamp));
		}
	}
	/**
	 * 用户登录完毕后设置鉴权参数
	 * @param userId
	 * @param sessionToken
	 * @param secretKey
	 */
	public void setAuthParam(String userId,String sessionToken,String secretKey){
		this.userId=userId;
		this.sessionToken=sessionToken;
		this.secretKey=secretKey;
		this.authed=true;
	}
}
